package com.xx.secret.util;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Enumeration;
import java.util.StringJoiner;
import java.util.regex.Pattern;

/**
 * @author wangcheng
 * @date 2020/12/17
 */
@Slf4j
public class AppUtil {

    /**
     * ios userAgent 正则
     */
    public static String iosReg = "^[\\s\\S]*(iPhone|iOS|iPad|iPod)+[\\s\\S]*$";


    public static boolean isIosDevice(String userAgent) {
        Pattern pattern = Pattern.compile(iosReg, Pattern.CASE_INSENSITIVE);
        return pattern.matcher(userAgent).matches();
    }

    public static boolean isIosDevice() {
        HttpServletRequest request = getRequest();
        if (request == null) {
            return false;
        }
        String userAgent = request.getHeader(HttpHeaders.USER_AGENT);
        if (StringUtils.isBlank(userAgent)) {
            return false;
        }
        return isIosDevice(userAgent);
    }


    public static HttpServletRequest getRequest() {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if (requestAttributes == null) {
            return null;
        }
        return ((ServletRequestAttributes) requestAttributes).getRequest();
    }

    public static String getLat(){
        HttpServletRequest request = getRequest();
        if (request == null){
            return "";
        }
        return request.getHeader("Lat");
    }

    public static String getLon(){
        HttpServletRequest request = getRequest();
        if (request == null){
            return "";
        }
        return request.getHeader("Lon");
    }

    public static String getDeviceId(){
        HttpServletRequest request = getRequest();
        if (request == null){
            return "";
        }
        return request.getHeader("deviceId");
    }

    public static String getHeaderStr(String headerName){
        HttpServletRequest request = getRequest();
        if (request == null){
            return "";
        }
        return request.getHeader(headerName);
    }

    public static JSONObject getParam() {
        JSONObject formBody = null;
        String contentType = AppUtil.getRequest().getContentType();
        //log.info("获取请求头: {} ",contentType);
        if (MediaType.APPLICATION_FORM_URLENCODED_VALUE.equals(contentType)){
            formBody = AppUtil.getParamsFromBody();
        }else if (MediaType.APPLICATION_JSON_VALUE.equals(contentType) || MediaType.APPLICATION_JSON_UTF8_VALUE.equals(contentType)
                || StringUtils.contains(contentType,"application/json")){
            formBody = AppUtil.getParamFromJson();
        }
        return formBody;
    }


    /**
     * json获取方式
     * @return
     */
    public static JSONObject getParamFromJson() {
        HttpServletRequest request = AppUtil.getRequest();
        BufferedReader bReader = null;
        InputStreamReader isr = null;
        try {
            InputStream iis = request.getInputStream();
            isr = new InputStreamReader(iis, "utf-8");
            bReader = new BufferedReader(isr);
            String str = null;
            StringBuffer buffer = new StringBuffer();

            while ((str = bReader.readLine()) != null) {
                buffer.append(str).append("\n");
            }
//            log.info(buffer.toString());
            JSONObject json =  JSONObject.parseObject(buffer.toString());
            return json;
        } catch (IOException e) {
        } finally {
            try {
                bReader.close();
            } catch (IOException e) {
            }
            try {
                isr.close();
            } catch (IOException e) {
            }
        }
        return new JSONObject();
    }

    /**
     * 表单获取方式
     * @return
     */
    public static JSONObject getParamsFromBody() {
        HttpServletRequest request = getRequest();
        //Map<String, String> params = new HashMap<>(16);
        JSONObject params = new JSONObject();
        Enumeration<String> parameterNames = request.getParameterNames();
        StringJoiner sj = new StringJoiner("&");
        while (parameterNames.hasMoreElements()) {
            String key = parameterNames.nextElement();
            String value = request.getParameter(key);
            if (StringUtils.isNoneEmpty(value)) {
                params.put(key, value);
                sj.add(key + "=" + value);
            }
        }
        //log.info("xx-form报文：{}", sj.toString());
        return params;
    }

}
